// import './style.less';

import * as THREE from 'three';
// import * as TWEEN from '@tweenjs/tween.js';
import * as TWEEN from 'three/examples/jsm/libs/tween.module';
import {GUI} from 'three/examples/jsm/libs/lil-gui.module.min.js';
import Stats from 'three/examples/jsm/libs/stats.module.js';

import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { TransformControls} from 'three/examples/jsm/controls/TransformControls.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';

let enableLightHelper = true;//是否开启灯光帮助器
let enableLightCameraHelper= false;//是否开启灯光相机帮助器
let updateObjects=[];//需要更新的物体列表

let container, scene, camera, renderer;//three.js的容器、场景、相机、渲染器
let cameraPersp ,cameraOrtho;//透视相机、正交相机
let mesh,meshWithTexture;//物体、带贴图的物体
let floor;//地板
let orbitControls;//轨道控制器
let stats;//性能监视器
let gui;//参数面板
let raycaster;//光线投射器
let raycasterHandlers = [];//光线投射器事件处理器   
let clickEnabledMeshs=[];//可点击的物体集合
let selectEnabledMeshs=[];//可可选择的物体集合


const clock = new THREE.Clock();//时钟
const gltfLoader = new GLTFLoader();//gltf加载器
const textureLoader = new THREE.TextureLoader();//贴图加载器

//准备材质
//基础材质
const basicMaterial = new THREE.MeshBasicMaterial({ 
    transparent: true,
    opacity: 0.5,
    color: 0x793e3e,
    side: THREE.DoubleSide,
    // wireframe: true,
});  
//高光材质
const phongMaterial = new THREE.MeshPhongMaterial({ 
    color: 0x793e3e,
    side: THREE.DoubleSide,
    shininess: 30,
    // wireframe: true,
});  
//哑光材质
const shadowMaterial = new THREE.MeshLambertMaterial({ 
    color: 0x793e3e,
    side: THREE.DoubleSide,
    // wireframe: true,
});  
//标准材质
const standardMaterial = new THREE.MeshStandardMaterial({ 
    transparent: true,
    opacity: 0.5,
    color: 0x793e3e,
    // color: 0x000000,
    side: THREE.DoubleSide,
    metalness:0.25,//金属度 0 非金属 1 金属
    roughness:0,//粗糙度 0 无粗糙 1 粗糙
});  

//物理材质
const physicalMaterial = new THREE.MeshPhysicalMaterial({ 
    color: 0x793e3e,
    // color: 0x888888,
    side: THREE.DoubleSide,
    metalness:0.25,//金属度 0 非金属 1 金属
    roughness:0,//粗糙度 0 无粗糙 1 粗糙

    transmission:0.9//透射率 1 完全透明 0 完全不透明
});  


//const texture = textureLoader.load('textures/hall.png');
const bodyMaterial = new THREE.MeshPhysicalMaterial({   
        side: THREE.DoubleSide,
        color:'red',
        metalness:1,//金属度 0 非金属 1 金属
        roughness:0.5,//粗糙度 0 光滑 1 粗糙

        clearcoat:1,//外层层厚度 0 无外层层 1 最大外层层厚度
        clearcoatRoughness:0.5//外层层粗糙度 0 无外层层 1 最大外层层粗糙度       
});//车身材质

//玻璃材质
const bodyGlassMaterial = new THREE.MeshStandardMaterial({   
    color: 0x000000,
    metalness:0.2,//金属度 0 非金属 1 金属
    roughness:0.1//粗糙度 0 无粗糙 1 粗糙    
});//车身玻璃材质

//地板材质
const floorMaterial = new THREE.MeshStandardMaterial({   
    color: 0x808080,
    side: THREE.DoubleSide,
    metalness:0,//金属度 0 非金属 1 金属
    roughness:0.1//粗糙度 0 无粗糙 1 粗糙
});//地板材质

//初始化容器
container=document.getElementById('app');

//初始化场景
function initScene() {    
    scene = new THREE.Scene();   
 }

 //初始化相机
 function initCamera() {
    const { clientWidth, clientHeight } = container;
    cameraPersp =  new THREE.PerspectiveCamera(75, clientWidth / clientHeight, 0.1, 1000);// 创建透视相机
    cameraOrtho = new THREE.OrthographicCamera(clientWidth / - 16, clientWidth / 16, clientHeight / 16, clientHeight / - 16, 0.1, 1000);// 创建正交相机
       
    camera = cameraPersp;//默认使用透视相机
    camera.position.y = 2;//相机位置y
    camera.position.z = 10;//相机位置z
    camera.lookAt(0, 0, 0);// 相机看向坐标原点
 }

 //初始化渲染器
 function initRenderer() {
    renderer = new THREE.WebGLRenderer({
        antialias: true
    });
    renderer.setPixelRatio(window.devicePixelRatio);       
    renderer.setSize(container.clientWidth, container.clientHeight);

    renderer.shadowMap.enabled = true;
    // renderer.shadowMap.type = THREE.PCFSoftShadowMap;

    container.appendChild(renderer.domElement);
 }

 //初始化环境光源
 function initAmbientLight() {
    const ambientLight = new THREE.AmbientLight(0xffffff, 7);
    scene.add(ambientLight);
 }
//初始化平行光源
function initDirectionalLight() {
    const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
    directionalLight.position.set(0, 3, 0);
    directionalLight.target.position.set(-10, 0, 0);

    directionalLight.castShadow = true;
    // directionalLight.shadow.mapSize.width = 1024;
    // directionalLight.shadow.mapSize.height = 1024;

    // directionalLight.shadow.camera.near = 0.2;
    // directionalLight.shadow.camera.far = 500;
    // directionalLight.shadow.camera.left = -50;
    // directionalLight.shadow.camera.right = 50;
    // directionalLight.shadow.camera.top = 50;
    // directionalLight.shadow.camera.bottom = -50;

    scene.add(directionalLight);

    if(enableLightHelper){
        //方向光帮助器
        const directionalLightHelper = new THREE.DirectionalLightHelper(directionalLight, 1);
        scene.add(directionalLightHelper);
    }
    if(enableLightCameraHelper){
        //方向光相机帮助器
        const cameraHelper = new THREE.CameraHelper(directionalLight.shadow.camera);
        scene.add(cameraHelper);
    }
}

//初始化点光源
function initPointLight() {
    const pointLight = new THREE.PointLight(0xffffff, 9); 

    pointLight.position.set(1, 3, 1); 
    scene.add(pointLight);          

    //点光源阴影
    pointLight.castShadow = true;   
    // pointLight.shadow.mapSize.width = 1024;
    // pointLight.shadow.mapSize.height = 1024;

    //pointLight产生PerspectiveCamera 透视相机
    pointLight.shadow.camera.near = 0.5;
    pointLight.shadow.camera.far = 500; 
    // pointLight.shadow.camera.aspect = 1; 
    // pointLight.shadow.camera.fov = 70; 
    
    //点光源帮助器
    if(enableLightHelper){
        const pointLightHelper = new THREE.PointLightHelper( pointLight,1 );
        scene.add( pointLightHelper );
        
    }

    //点光源相机帮助器
    if(enableLightCameraHelper){
        const cameraHelper = new THREE.CameraHelper( pointLight.shadow.camera );
        scene.add( cameraHelper );
        //selectEnabledMeshs.push(cameraHelper);//可选中物体列表中添加可选中物体
    }
}

//初始化聚光灯
function initSpotLight() {
    const spotLight = new THREE.SpotLight(0xffffff, 2);
    spotLight.angle = Math.PI / 4;//光照角度 弧度制    
    spotLight.penumbra = 0.1;//光照扩散范围 0 无扩散 1 扩散至原点    
    spotLight.decay = 2; //衰减系数 值越大衰减越快    
    spotLight.distance = 0; //光照距离 0 无限远    
        
    spotLight.position.set(0, 3, 0);//光源位置    
    spotLight.target.position.set(0, 0, 0);//光源目标点    
    
    spotLight.castShadow = true; //是否投射阴影    
    // spotLight.shadow.map.type = THREE.PCFSoftShadowMap; //阴影贴图类型    
    spotLight.shadow.mapSize.width = 1024;//阴影贴图大小    
    spotLight.shadow.mapSize.height = 1024;//阴影贴图大小    
    
    //透视相机
    // spotLight.shadow.camera.near = 0.1; //阴影相机近端面    
    // spotLight.shadow.camera.far = 100; //阴影相机远端面    
    // spotLight.shadow.camera.fov = 90; //阴影相机视角度  
    // spotLight.shadow.camera.aspect = 1; //阴影相机纵横比    
    
    //spotLight.shadow.bias = -0.001; //阴影偏移量 值越大偏移越大   

    scene.add(spotLight);

    // //聚光灯帮助器
    if(enableLightHelper){
        const spotLightHelper = new THREE.SpotLightHelper( spotLight );
        scene.add( spotLightHelper );
    }

    //聚光灯相机帮助器
    if(enableLightCameraHelper){
        const cameraHelper= new THREE.CameraHelper( spotLight.shadow.camera );
        scene.add( cameraHelper );
    }
    
}

 //初始化全局坐标轴
 function initAxesHelper() {
    const axesHelper = new THREE.AxesHelper(3);
    scene.add(axesHelper);
 }

 //初始化网格
 function initGridHelper() {
    const gridHelper = new THREE.GridHelper(20, 20,'red',0xffffff);
    gridHelper.material.opacity = 0.2;
    gridHelper.material.transparent = true;
    scene.add(gridHelper);
 }
 //初始化性能统计
 function initStats() {
    stats = new Stats();
    stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
    document.body.appendChild(stats.dom);
 }

 //初始立方物体
 function initMesh(material=null) {
    const geometry = new THREE.BoxGeometry(1, 1, 1);
    if(!material){
        material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });  
    }     
    mesh = new THREE.Mesh(geometry, material); 
    mesh.castShadow=true;   
    mesh.receiveShadow=true;   
    mesh.position.x = -1;
    scene.add(mesh);//场景中添加立方体
    selectEnabledMeshs.push(mesh);//可选中物体列表中添加可选中物体
 }

 //初始化地板
 function initFloor() {
    const geometry = new THREE.PlaneGeometry(20, 20);
    const material = new THREE.MeshStandardMaterial({ 
        color: 0x808080 ,
        side: THREE.DoubleSide,
        metalness:0,//金属度 0 非金属 1 金属
        roughness:0.1//粗糙度 0 无粗糙 1 粗糙
    });
    floor = new THREE.Mesh(geometry, material);
    floor.name = 'floor';
    floor.rotation.x = - Math.PI / 2;

    floor.receiveShadow = true;

    scene.add(floor);//场景中添加地板
    clickEnabledMeshs.push(floor);//可点击物体列表中添加可点击物体
    selectEnabledMeshs.push(floor);//可选中物体列表中添加可选中物体
 }

  //初始带有纹理贴图的立方物体
  function initMeshWithTexture() {
    const geometry = new THREE.BoxGeometry(1, 1, 1);
    const material = new THREE.MeshStandardMaterial({ 
        color: 'red' ,
        map: textureLoader.load('textures/hall.png')
    });    
    meshWithTexture  = new THREE.Mesh(geometry, material);    
    meshWithTexture.position.x = 1;
    scene.add(meshWithTexture);//场景中添加立方体

    selectEnabledMeshs.push(meshWithTexture);//可选中物体列表中添加可选中物体
 }

//初始化GUI
function initGui() {
    gui = new GUI();
    const mesh = floor; //指定mesh为地板

    const folder1 = gui.addFolder("自定义控制台输出");
    let options = {
      color: "red",
      isOpen: true,
    };
    folder1.add(options, "isOpen").onFinishChange(function (value) {
      console.log(value);
    }).name("是否开启");
    folder1
        .add(options, "color", ["red", "green", "blue"])
        .onFinishChange(function (value) {
          console.log(value);
          switch (value) {
            case "red":
              // mesh.material.color.set(0xff0000);
              // console.log("red");
              break;
            case "green":
              // mesh.material.color.set(0x00ff00);
              // console.log("green");
              break;
            case "blue":
              // mesh.material.color.set(0x0000ff);
              // console.log("blue");
              break;
          }
        });
    
    if (mesh) {      
      const leftMove = () => {
        // this.setAnimation({ x: 0 }, { x: Math.PI / 4 }, mesh);
        mesh.position.x += -1;
      };
      const rightMove = () => {
        mesh.position.x += 1;
      };
      let floorOptions = {       
        floorColor: 0x00ff00,
        leftMove,
        rightMove,
      };
      const folder = gui.addFolder("地板");
      //添加子项
      folder.add(mesh.position, "x", -5, 5).step(0.1).name("X轴位置");
      folder.add(mesh.position, "y", -5, 5).step(0.1).name("Y轴位置");
      folder.add(mesh.position, "z", -5, 5).step(0.1).name("Z轴位置");

      folder
        .addColor(floorOptions, "floorColor")
        .name("颜色")
        .onChange(function (value) {
          mesh.material.color.set(value);
        });
      folder.add(floorOptions, "leftMove").name("左移");
      folder.add(floorOptions, "rightMove").name("右移");
    }
}

 

//设置补间动画
function setAnimation(start, end, mesh, callback) {
    //const start={x:0,y:0,z:0};
    //const end={x:1,y:1,z:1};
    const tween = new TWEEN.Tween(start)
        .to(end, 1000).easing(TWEEN.Easing.Quadratic.Out);
    tween.onUpdate(function(that) {
        mesh.rotation.x=that.x;
        if(callback){
            callback(that);
        }   
    })
    tween.start();
}    

//加载模型
function loadModel() {        
    gltfLoader.load('models/hall.glb', function(gltf) {                        
        const model = gltf.scene;        
        scene.add(model);        
    });     
 }

//加载大厅模型
function loadHallModel() {        
    gltfLoader.load('models/hall.glb', function(gltf) {                        
        const model = gltf.scene;   
        console.log(model);
        model.traverse(function (obj) {
            console.log(obj.name);
            // if (obj.name === 'carBody') {
            //     obj.castShadow = true;
            // }
            // if (obj.isMesh) {
            //     obj.castShadow = true;
            //     obj.receiveShadow = true;
            // }          
            // if (child instanceof THREE.Mesh) {
                
            // }
        })
        scene.add(model);        
    });     
 }


 //渲染函数     
function render() {
    renderer.render(scene, camera); 
}  

//动画循环函数
function animate() {
    requestAnimationFrame(animate);    

    const delta = clock.getDelta();
    orbitControls.update();    
    TWEEN.update();

    if(stats)
      stats.update();//更新性能插件

    //更新物体
    updateObjects.forEach(function(updateObject) {
        updateObject.update(delta);
    });

    render();        
}

//入口函数
function main() {
    //threejs三要素初始化
    initScene();    
    initCamera();    
    initRenderer(); 

    //界面帮助初始化
    initAxesHelper();    
    initGridHelper();  
    

    //初始灯光
    // initAmbientLight();      
    initDirectionalLight();
    // initPointLight();
    // initSpotLight();

    //初始化物体
    initFloor();
    initMesh(bodyMaterial);  
    initMeshWithTexture();  
       
    // loadModel(); 
    // loadHallModel();

    //初始化控制器    
    initOrbitControls(); 
    initTransformControls(); 

    //初始化canvas内部元素点击事件处理
    initRaycaster();
    // initClickRaycaster();
    // initSelectRaycaster();

    initDomEventListener();
    initKeyboardEventListener();
    initGui();  

    //性能统计初始化
    initStats();

    //循环渲染动画
    animate();
}

//----------以下为控制器控制代码和Dom事件监听----------------------  
//初始化轨道控制器
function initOrbitControls() {
    orbitControls = new OrbitControls(camera, renderer.domElement);
    orbitControls.target.set(0, 0, 0);//控制器目标点

    orbitControls.enableDamping = true;//是否开启阻尼
    // orbitControls.dampingFactor = 0.05;//阻尼系数

    // orbitControls.enableZoom = false;//是否允许缩放 

    // orbitControls.enablePan = true;//是否允许拖拽
    // orbitControls.panSpeed = 0.5;//拖拽速度

    // orbitControls.enableRotate = true;//是否允许旋转
    // orbitControls.autoRotate = true;//是否自动旋转
    // orbitControls.autoRotateSpeed = 0.5;//自动旋转速度
    // orbitControls.rotateSpeed = 0.5;//旋转速度

    
    // orbitControls.screenSpacePanning = true;//是否允许屏幕空间拖拽
    
    // orbitControls.minDistance = 1;//最小距离
    // orbitControls.maxDistance = 10;//最大距离
    
    // orbitControls.minPolarAngle = 0;//最小倾角
    // orbitControls.maxPolarAngle = Math.PI/4 ;//最大倾角

    // orbitControls.minAzimuthAngle = - Math.PI / 2;//最小方位角
    // orbitControls.maxAzimuthAngle = Math.PI / 2;//最大方位角    

 }

 //初始化变换控制器
 let transformControls;//变换控制器
 function initTransformControls() {
     transformControls = new TransformControls(camera, renderer.domElement);
     transformControls.setSpace( 'local' );
     transformControls.setMode( 'translate');

     transformControls.addEventListener('dragging-changed', (e)=>{
        // console.log("transformControlsdragging-changed",e);
        orbitControls.enabled = !e.value;//是否开启轨道控制器
     });
     transformControls.addEventListener('objectChange', (e)=>{
        //console.log("transformControlsobjectChange",e);
        const {position,rotation,scale} = transformControls.object;
        console.log("objectChange",JSON.stringify({position,rotation:{x:rotation.x,y:rotation.y,z:rotation.z},scale})); //获取变换后的位置
     });//物体变换事件
     scene.add(transformControls);
 }


//初始化射线投射器
function initRaycaster() {
    raycaster = new THREE.Raycaster();
    raycasterHandlers = [];

    //获取父级是场景的物体
    function getParent(obj3d){
      if(obj3d.parent.isScene){
          return obj3d;
      }else if(obj3d.parent){
          return getParent(obj3d.parent);
      }else{
          return null;
      }
    }


    //点击事件变成可点击物体变换控制器
    addRaycasterListener("select",selectEnabledMeshs,
      (intersect) => {
        console.log("select", intersect);
        const control = transformControls;
        const parent = getParent(intersect.object);
        control.attach(intersect.object); // 绑定变换控制器
        control.enabled = true; // 启用变换控制器
        control.showX = true;
        control.showY = true;
        control.showZ = true;
      }
    );

    // //点击事件处理
    // addRaycasterListener("click", clickEnabledMeshs, (intersect) => {
    //   console.log("click", intersect);
    // });

    // removeRaycasterListener("select",handleIntersect);

    // function handleIntersect(intersect) {
    //   console.log("handleIntersect",intersect);
    // }
    // addRaycasterListener("select",selectEnabledMeshs,handleIntersect);

    // addRaycasterListener("select",selectEnabledMeshs,(intersect)=>{
    //   console.log("select",intersect);
    // });
  }
  //移除canvas内部元素点击事件处理
function  removeRaycasterListener(eventName, callback) {
    // debugger
    if (raycasterHandlers.length > 0) {
      if (callback) {
        const index = raycasterHandlers.findIndex(
          (item) => item.eventName === eventName && item.callback === callback
        );
        if (index >= 0) {
          const handler = raycasterHandlers[index].handler;
          options.container.removeEventListener("click", handler);
          raycasterHandlers.splice(index, 1);
        }
      } else {
        for (let i = raycasterHandlers.length - 1; i >= 0; i--) {
          if (raycasterHandlers[i].eventName === eventName) {
            const handler = raycasterHandlers[i].handler;
            options.container.removeEventListener("click", handler);
            raycasterHandlers.splice(i, 1);
          }
        }
      }
    }
  }
  //添加canvas内部元素点击事件处理
function  addRaycasterListener(eventName, enableMeshs = [], callback) {
    const pointer = new THREE.Vector2();
    const handler = (event) => {
      const { clientWidth, clientHeight } = container; // 获取容器宽高
      pointer.x = (event.clientX / clientWidth) * 2 - 1;
      pointer.y = -(event.clientY / clientHeight) * 2 + 1;

      raycaster.setFromCamera(pointer, camera); // 设置射线
      const intersects = raycaster.intersectObjects(enableMeshs); // 计算射线经过的所有可点击物体
      const intersect = intersects[0];
      if (intersect) {
        callback(intersect);
      }
    };
    container.addEventListener("click", handler);
    raycasterHandlers.push({ eventName, handler, callback: callback });
  }


//初始化键盘监听事件处理
function initKeyboardEventListener() { 
    camera = cameraPersp;//切换默认相机为透视相机
    //处理键盘事件
    window.addEventListener( 'keydown', function ( event ) {   
      console.log(transformControls.object);//获取变换控制器的物体
      if(!transformControls.object)//如果没有物体被选中，则不处理键盘事件
        return;

      switch (event.keyCode ) {
        case 81: // Q
          transformControls.setSpace( transformControls.space === 'local' ? 'world' : 'local' );
          break;

        case 16: // Shift
          transformControls.setTranslationSnap( 100 );
          transformControls.setRotationSnap( THREE.MathUtils.degToRad( 15 ) );
          transformControls.setScaleSnap( 0.25 );
          break;

        case 84: // T
          transformControls.setMode( 'translate' );
          break;

        case 82: // R
          transformControls.setMode( 'rotate' );
          break;

        case 83: // S
          transformControls.setMode( 'scale' );
          break;

        case 67: // C
          const position = camera.position.clone();//获取相机位置克隆
          //切换相机类型
          camera = camera.isPerspectiveCamera ? cameraOrtho : cameraPersp;
          camera.position.copy( position );//设置相机位置

          orbitControls.object = camera;//设置轨道控制器的目标物体
          transformControls.camera = camera;//设置变换控制器的相机

          //更新相机视角
          camera.lookAt( orbitControls.target.x, orbitControls.target.y, orbitControls.target.z );
          onWindowResize();
          break;

        case 86: // V
          const randomFoV = Math.random() + 0.1;
          const randomZoom = Math.random() + 0.1;

          cameraPersp.fov = randomFoV * 160;
          cameraOrtho.bottom = - randomFoV * 500;
          cameraOrtho.top = randomFoV * 500;

          cameraPersp.zoom = randomZoom * 5;
          cameraOrtho.zoom = randomZoom * 5;
          onWindowResize();
          break;

        case 187:
        case 107: // +, =, num+
          transformControls.setSize( transformControls.size + 0.1 );//变换控制器大小
          break;

        case 189:
        case 109: // -, _, num-
          transformControls.setSize( Math.max( transformControls.size - 0.1, 0.1 ) );//变换控制器大小
          break;

        case 88: // X
          transformControls.showX = ! transformControls.showX;//显示/隐藏X轴
          break;

        case 89: // Y
          transformControls.showY = ! transformControls.showY;//显示/隐藏Y轴
          break;

        case 90: // Z
          transformControls.showZ = ! transformControls.showZ;//显示/隐藏Z轴
          break;

        case 32: // Spacebar
          transformControls.enabled = ! transformControls.enabled; //变换控制器开关
          if(!transformControls.enabled){   
            transformControls.detach();
          }        
        //   if(transformControls.object){
        //     if(transformControls.enabled){           
        //       transformControls.showX = true;
        //       transformControls.showY = true;
        //       transformControls.showZ = true;
        //       //transformControls.attach(transformControls.object );                
        //     }
        //     else{
        //       transformControls.showX = false;
        //       transformControls.showY = false;
        //       transformControls.showZ = false;
        //       //transformControls.detach();
        //     }
        //   }else{
           
        //   }        
          break;

        case 27: // Esc
          transformControls.reset();
          break;

      }});
}

//窗口大小改变时，更新渲染器大小
function onWindowResize() {
    const {clientWidth, clientHeight} = container;// 获取容器宽高
    const aspect = clientWidth / clientHeight;// 计算宽高比

    cameraPersp.aspect = aspect;//设置透视相机纵横比
    cameraPersp.updateProjectionMatrix();//更新透视相机投影矩阵

    // cameraOrtho.left = cameraOrtho.bottom * aspect;//设置正交相机视域
    // cameraOrtho.right = cameraOrtho.top * aspect;//设置正交相机视域
    cameraOrtho.updateProjectionMatrix();//更新正交相机投影矩阵

    renderer.setSize( clientWidth, clientHeight );// 设置渲染器宽高

    // camera.aspect = clientWidth / clientHeight;
    // camera.updateProjectionMatrix();
    // renderer.setSize( clientWidth, clientHeight );// 设置渲染器宽高
}
//初始化Dom事件监听
function initDomEventListener() {
    //窗口大小改变时，更新渲染器大小    
    window.addEventListener('resize', onWindowResize, false);   
    
    //全屏显示
    const fullscreenButton = document.getElementById('btnFullscreen');
    fullscreenButton.addEventListener('click', toggleFullscreen, false);
    
}  

//全屏显示
function toggleFullscreen() {
    const isFullscreen = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
    if (isFullscreen) {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
    } else {   
        const container = document.body;
        if (container.requestFullscreen) {
            container.requestFullscreen();
        } else if (container.webkitRequestFullscreen) {
            container.webkitRequestFullscreen();
        } else if (container.mozRequestFullScreen) {
            container.mozRequestFullScreen();
        } else if (container.msRequestFullscreen) {
            container.msRequestFullscreen();
        }
    }
}

//初始化程序
main();
       